package com.xcf.client;

import com.xcf.center.ServerMeta;
import com.xcf.center.client.IBalanceHandler;
import com.xcf.center.client.ServerWrapper;

import java.util.Comparator;
import java.util.List;
import java.util.Random;

/**
 * 负载均衡器
 */
public class WorkBalanceHandler implements IBalanceHandler<ServerMeta> {

    @Override
    public ServerWrapper<ServerMeta> balance(List<ServerWrapper<ServerMeta>> serverList) {
        serverList.sort(Comparator.comparingLong(ServerWrapper::getLastHandlerTime));
        Long minTime = serverList.get(0).getLastHandlerTime();
        int index = 0;
        for (ServerWrapper<ServerMeta> wrapper : serverList) {
            if (wrapper.getLastHandlerTime() <= minTime) {
                index++;
            }
        }
        Random random = new Random();
        int lastIndex = random.nextInt(index);
        return serverList.get(lastIndex);
    }

}
